<template>
  <div class="app-container">
     <!-- 标题 -->
   	<header class="app-header">
    	<span class="title">{{$route.meta.title}}</span>
			<!--
      <el-button type="primary" icon="el-icon-edit" @click.native="goToComment">评论列表</el-button>
      -->
      <el-button type="danger" icon="el-icon-delete" @click.native="allDelItem">批量删除</el-button>
    </header>
    <el-form :inline="true" :model="listQuery" class="query-form">
      <el-form-item>
        <el-input v-model="listQuery.name" clearable placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item>
      	<el-cascader :options="categories" clearable style=" width:320px;" :props="cateProps"  v-model="listQuery.categories" placeholder="请选择商品分类"></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button-group>
          <el-button type="primary" icon="el-icon-search"  @click="onSubmit">查询</el-button>
          <el-button type="primary" icon="el-icon-refresh"  @click="onSubmit">刷新</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
    <!-- 表单 -->

    <el-table v-loading="loading" :data="list" border  @selection-change="handleSelectionChange">
      <el-table-column align="center" width="50" type="selection"></el-table-column>
      <el-table-column align="center" label="商品ID" prop="id" width="120"></el-table-column>
      <el-table-column align="left" label="商品名称" show-overflow-tooltip>
      	<template slot-scope="scope">
        	<el-image fit="contain" lazy :src="scope.row.pics.length > 0 ? scope.row.pics[0].url : ''" class="pis-li-img">
            <div slot="error" class="pis-li-img">
              <i class="el-icon-picture-outline" style="font-size:30px; color:#DAE6EC; margin-top:9px;"></i>
            </div>
          </el-image>
        	{{ scope.row.name }}
        </template>
			</el-table-column>
      <el-table-column align="center"  label="所属分类" width="220" prop="categories" show-overflow-tooltip>
				<template slot-scope="scope">
        	 {{ scope.row.categories | parseCate(categories)}}
        </template>
			</el-table-column>
  		<el-table-column align="center" label="库存" prop="inventory" width="70"></el-table-column>

      <el-table-column align="center" label="状态" prop="status"  width="80" >
        <template slot-scope="scope">
          <span @click="changeStatus(scope.row)" style=" cursor:pointer; color:red" v-if="scope.row.status == '0'">下线</span>
          <span @click="changeStatus(scope.row)" style=" cursor:pointer;color:green" v-else-if="scope.row.status == '1'">上线</span>
        </template>
      </el-table-column>

			<el-table-column align="center" label="商品价格"  width="120"  show-overflow-tooltip>
        <template slot-scope="scope">
         	￥{{ scope.row.price | setMoney}}<br/>
          <del style=" color:#CCC;">￥{{ scope.row.marketPrice | setMoney}}</del>
        </template>
      </el-table-column>


      <el-table-column align="center"  width="150" label="操作">
      	<el-button-group slot-scope="scope">
   				<el-button type="primary" size="mini" @click.native.prevent="editWare(scope.row,scope.$index)">编辑</el-button>
          <el-button type="danger" size="mini"  @click.native.prevent="handleDel(scope.$index, scope.row)">删除</el-button>
        </el-button-group>
      </el-table-column>

    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList"/>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import request from '@/utils/request'
import config from '@/api/bgapi'
import { parseTime } from '@/utils'
export default {
  components: { Pagination},
  data() {
    return {
      loading: false,
			categories:[],
			cateProps:{children: 'children', label: 'cateName' ,value:'id'},
      list:[],
      total: 0,
      listQuery: {
        title: '',
        page: this.$route.query.page?Number(this.$route.query.page):1,
        pageSize: 20
      }
    }
  },
  mounted(){
    this.selectItme = [];
    this.getList();
		this.getShopCate();
  },
  methods: {
		async getShopCate(){
			var res = await request.get(config.shopCate);
			if(res.code == '20000'){
				this.categories = res.data;
			}
		},
    onSubmit() {
      this.getList()
    },
    async getList() {
      this.loading = true;
      var res = await request.get(config.goods,{ params:this.listQuery } );
      this.loading = false;
      this.list = res.data || [];
      this.total = res.totalNum || 0;
    },
    handleSelectionChange(val){
      this.selectItme = val;
    },
    allDelItem(){
      if(this.selectItme.length == 0){return}
      this.$confirm("确认删除所选记录吗?", "提示", {
          type: "warning",
      })
      .then(async () => {
          let _ids = this.selectItme.map((item,index) =>{ return item.id});
          var res = await request.post(config.delManyGoods,{ids:_ids});
          if(res.code == '20000'){
            this.$message.success("删除成功");
            this.getList();
          }
      })
      .catch(() => {
          this.$message.info("取消删除");
      });
    },
    handleDel(index, row){
      if (row.id) {
        this.$confirm("确认删除该记录吗?", "提示", {
            type: "warning",
        })
        .then(async () => {
            var res = await request.delete(config.goods+'/'+row.id);
            if(res.code == '20000'){
              this.$message.success("删除成功");
              this.getList();
            }
        })
        .catch(() => {
            this.$message.info("取消删除");
        });
      }
    },
		goToComment(){
			this.$router.push({path:'/content/list/comment'});
		},
    async editWare(row,index){
			this.$router.push({path:'/shop/goodlist/edit',query: {id:row.id}})
    },
		async changeStatus(_item){
			var _id = _item.id;
			var _status = _item.status == 0 ? 1 : 0;
			var _params = {status:_status};
			var res = await request.put(config.goods+'/'+_id,_params);
			if(res.code == '20000'){
				this.$message.success('修改成功！');
				this.getList();
			}else{
				this.$message.error('修改失败，请联系管理员！');
			}
		}
  },
  filters: {
		setMoney(money){
			if(money){
				money = money.toFixed(2)
			}else{
				money = 0;
				money = money.toFixed(2)
			}
			return money;
		},
		parseCate(cateIds,cateArr){
			var arr = cateIds;
			var data = cateArr;
			function getCity(arr, data, city = []) {
				if (typeof data === "object") {
						for (let i = 0; arr[i] !== undefined; i++) {
								for (let j = 0; data[j] !== undefined; j++) {
										if (arr[i] === data[j].id) {
												city.push(data[j].cateName);
										}
								}
						};
						for (let i = 0; data[i] !== undefined; i++) {
								getCity(arr, data[i].children, city);
						};
				}
				return city;
			}

			var str = getCity(arr,data).join('/')

			return str;
		}
  },
}
</script>
<style scoped>
.pis-li-img{ display:inline-block; text-align:center; width:50px; height:50px; cursor:pointer; border:1px solid #DDE6EC; vertical-align:middle;}
</style>
